package cn.tedu.user.controller;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import org.apache.commons.lang.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import cn.tedu.common.pojo.SysResult
import cn.tedu.common.pojo.User
import cn.tedu.common.utils.CookieUtils
import cn.tedu.staticResources.RedisRelative
import cn.tedu.user.service.UserService

@RestController
@RequestMapping(Array("user/manage"))
class UserController {

  @Autowired
  private var userService: UserService = _

  @RequestMapping(Array("checkUserName"))
  def checkUserName(userName: String) = {
    if (userService.checkUserName(userName) == 1) SysResult build (201, "不可用", null) else SysResult ok
  }

  @RequestMapping(Array("save"))
  def saveUser(user: User) = {
    try {
      userService saveUser user; SysResult ok
    } catch {
      case t: Exception => t.printStackTrace(); SysResult.build(201, t.getMessage(), null)
    }
  }

  @RequestMapping(Array("login"))
  def doLogin(user: User, req: HttpServletRequest, res: HttpServletResponse) = {
    val ticket = userService doLogin user
    if (StringUtils.isNotEmpty(ticket)) {
      CookieUtils.setCookie(req, res, RedisRelative.cookieName, ticket)
      SysResult ok
    } else {
      SysResult.build(201, "", null)
    }
  }

  @RequestMapping(Array("query/{ticket}"))
  def queryTicket(@PathVariable ticket: String) = {
    val userJson = userService.queryTicket(ticket)
    if (!StringUtils.isNotEmpty(userJson)) SysResult.build(201, "", null) else SysResult.build(200, "ok", userJson)
  }
}